package il.technion.cs236369.webserver;

import java.util.Arrays;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;

public class JavaCompile {

	private final JavaCompiler compiler;
	private final StandardJavaFileManager manager;

	public JavaCompile(String compilerPath) {
		compiler = ToolProvider2.getSystemJavaCompiler(compilerPath);
		if (compiler == null) {
			throw new RuntimeException("compiler not found");
		}
		manager = compiler.getStandardFileManager(null, null, null);
		if (manager == null) {
			throw new RuntimeException("compiler returned null file manager");
		}
	}

	public Class<?> compileAndLoad(String srcPath,String qualifiedClassName) throws ClassNotFoundException {
		Iterable<? extends JavaFileObject> units = manager.getJavaFileObjects(srcPath);
		Boolean status = compiler.getTask(null, manager, null,
				Arrays.asList(new String[] { "-d", "bin" }), null, units).call();
		if (status == null || !status.booleanValue()) {
			System.out.println("Compilation failed");
			return null;
		} else {
			System.out.printf("Compilation successful!!!\n");
		}

		return manager.getClassLoader(javax.tools.StandardLocation.CLASS_PATH).loadClass (qualifiedClassName);
	}

	@Override
	protected void finalize() throws Throwable {
		if (manager != null)
			manager.close();
		super.finalize();
	}

}
